import React, { useEffect, useState } from 'react'
import { Descriptions, Button } from 'antd'
import { HeartTwoTone } from '@ant-design/icons'
import { useParams } from 'react-router-dom'
import moment from 'moment'
import { useNavigate } from 'react-router'
import { getNewsInfoApi, updateNewsApi } from '@/api/news'

function Detail() {
  const navigate = useNavigate()
  const [newsInfo, setNewsInfo] = useState(null)
  const params = useParams()

  useEffect(() => {
    getNewsInfo()
  }, [params])

  // 获取新闻详情
  const getNewsInfo = () => {
    getNewsInfoApi(params.id).then(res => {
      setNewsInfo(res)
      updateNewsApi(params.id, {
        ...res,
        view: res.view + 1
      })
      setNewsInfo({
        ...res,
        view: res.view + 1
      })
    })
  }

  // 点赞
  const handleStar = () => {
    updateNewsApi(params.id, {
      ...newsInfo,
      star: newsInfo.star + 1
    }).then(() => {
      getNewsInfo()
    })
  }

  return (
    <div style={{ padding: '15px' }}>
      <Descriptions
        extra={
          <>
            <HeartTwoTone
              onClick={() => {
                handleStar()
              }}
              twoToneColor="#eb2f96"
            />
            &nbsp;&nbsp;
            <Button onClick={() => navigate(-1)} type="primary">返回</Button>
          </>

        }
        title={newsInfo?.title}
      >
        <Descriptions.Item label="创建者">{newsInfo?.author}</Descriptions.Item>
        <Descriptions.Item label="发布时间">{newsInfo?.publishTime ? moment(newsInfo?.createTime).format('YYYY/MM/DD HH:mm:ss') : '-'}</Descriptions.Item>
        <Descriptions.Item label="区域">{newsInfo?.region}</Descriptions.Item>
        <Descriptions.Item label="访问数量">{newsInfo?.view}</Descriptions.Item>
        <Descriptions.Item label="点赞数量">{newsInfo?.star}</Descriptions.Item>
        <Descriptions.Item label="评论数量">0</Descriptions.Item>
      </Descriptions>

      <div dangerouslySetInnerHTML={{
        __html: newsInfo?.content
      }} style={{
        border: '1px solid gray'
      }}>
      </div>
    </div>
  )
}

export default Detail